package com.qsmx.store.app.main.mem;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatTextView;
import android.view.View;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qsmx.store.app.R;
import com.qsmx.store.app.R2;
import com.qsmx.store.app.event.CardReadEvent;
import com.qsmx.store.app.fustion.FustionManager;
import com.qsmx.store.app.http.HttpHelper;
import com.qsmx.store.app.http.HttpUrl;
import com.qsmx.store.app.main.mem.entity.MemCardSaleEntity;
import com.qsmx.store.app.main.mem.entity.MemCardSellInfoEntity;
import com.qsmx.store.app.util.CardReadUtil;
import com.qsmx.store.app.util.StringUtil;
import com.qsmx.store.core.delegates.AtmosDelegate;
import com.qsmx.store.core.fusion.FusionCode;
import com.qsmx.store.core.net.callback.IError;
import com.qsmx.store.core.net.callback.IFailure;
import com.qsmx.store.core.net.callback.ISuccess;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.List;
import java.util.WeakHashMap;

import butterknife.BindView;
import butterknife.OnClick;

public class MemCardBackDelegate extends AtmosDelegate {

    private char mCardIcTag = 0x04;
    private char mCardNoTag = 0x3c;
    private boolean isReadNow = false;
    private MemCardSellInfoEntity mCardSellInfoData;

    @BindView(R2.id.tv_ic_card_num)
    AppCompatTextView tvIcCardNum;
    @BindView(R2.id.iv_card_scan)
    AppCompatImageView ivCardScan;
    @BindView(R2.id.tv_mem_card_num)
    AppCompatTextView tvMemCardNum;
    @BindView(R2.id.tv_mem_level)
    AppCompatTextView tvMemLevel;
    @BindView(R2.id.tv_mem_less_coin)
    AppCompatTextView tvMemLessCoin;
    @BindView(R2.id.tv_mem_less_point)
    AppCompatTextView tvMemLessPoint;
    @BindView(R2.id.tv_mem_less_ticket)
    AppCompatTextView tvMemLessTicket;
    @BindView(R2.id.tv_mem_back_money)
    AppCompatTextView tvMemBackMoney;
    @BindView(R2.id.et_mem_remark)
    AppCompatEditText etMemRemark;

    @OnClick(R2.id.tv_sure_back)
    void onSureBack() {

        if (mCardSellInfoData != null) {
            JSONObject params = new JSONObject();
            params.put("deptId", FustionManager.mMachineData.getDeptId());
            params.put("billNo", mCardSellInfoData.getCardSell().getBillNo());
            params.put("remainCoin", mCardSellInfoData.getMemberProperty().getCoins());
            params.put("remainTicket", mCardSellInfoData.getMemberProperty().getTickets());
            params.put("remainIntegral", mCardSellInfoData.getMemberProperty().getIntegrals());
            params.put("businessDate", FustionManager.mMachineData.getBusinessDate());
            params.put("machineId", FustionManager.mMachineData.getMachineId());
            params.put("machineCode", FustionManager.mMachineData.getMachineCode());
            params.put("remark", etMemRemark.getText().toString());
            HttpHelper.RestClientPostRaw(params, HttpUrl.SELL_CARD_REFUND,
                    new ISuccess() {
                        @Override
                        public void onSuccess(int code, String response) {
                            setAllClean();
                            showShortToast("退单成功");
                        }
                    }, new IError() {
                        @Override
                        public void onError(int code, String msg) {
                            showShortToast(msg);
                        }
                    }, new IFailure() {
                        @Override
                        public void onFailure() {

                        }
                    });

        } else {
            showShortToast("请先查询订单");
        }

    }

    private void setAllClean() {

        mCardSellInfoData = null;
        tvIcCardNum.setText("");
        tvMemBackMoney.setText("");
        tvMemCardNum.setText("");
        tvMemLessCoin.setText("");
        tvMemLessPoint.setText("");
        tvMemLessTicket.setText("");
        tvMemLevel.setText("");
        etMemRemark.setText("");
    }

    @OnClick(R2.id.iv_card_scan)
    void onCardScan() {
        if (!isReadNow) {
            CardReadUtil.StartGetCardNum(getContext(), mCardIcTag, new CardReadEvent(new Bundle()));
            isReadNow = true;
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_mem_back_card;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {

    }

    private void onGetCardInfo(String cardNum) {
        WeakHashMap<String, Object> params = new WeakHashMap<>();
        params.put("deptId", FustionManager.mMachineData.getDeptId());
        params.put("icNo", cardNum);

        HttpHelper.RestClientGet(params, HttpUrl.SELL_CARD_BILL,
                new ISuccess() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onSuccess(int code, String response) {
                        Type type = new TypeToken<MemCardSellInfoEntity>() {
                        }.getType();
                        Gson gson = new Gson();
                        mCardSellInfoData = gson.fromJson(response, type);

                        tvIcCardNum.setText(mCardSellInfoData.getCardSell().getIcNo());
                        tvMemCardNum.setText(mCardSellInfoData.getCardSell().getMemberNo());
                        tvMemLevel.setText(mCardSellInfoData.getCardSell().getGradeName());
                        tvMemLessCoin.setText(String.valueOf(mCardSellInfoData.getMemberProperty().getCoins()));
                        tvMemLessPoint.setText(String.valueOf(mCardSellInfoData.getMemberProperty().getIntegrals()));
                        tvMemLessTicket.setText(String.valueOf(mCardSellInfoData.getMemberProperty().getTickets()));
                        tvMemBackMoney.setText("￥" + mCardSellInfoData.getCardSell().getActualMoney());

                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        showShortToast(msg);
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {

                    }
                });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CardReadEvent event) {
        if (event != null && event.getData() != null) {
            showShortToast("读卡成功");
            isReadNow = false;
            if (StringUtil.isNotEmpty(event.getData().getString("cardNum"))) {
                if (event.getData().getChar("tag") == mCardIcTag) {
                    onGetCardInfo(event.getData().getString("cardNum").substring(0, 18));
                }
            } else {
                showShortToast("这个卡是空的");
            }

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        FusionCode.SCAN_TYPE = FusionCode.CANCEL;
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }
}
